import http from 'node:http'
import https from 'node:https'
import url from 'node:url'
// console.log(new url.URL('https://localhost:80/aaaa/abc?A=1&b=2'))
/* 
 {
  href: 'https://localhost:80/aaaa/abc?A=1&b=2',
  origin: 'https://localhost:80',
  protocol: 'https:',
  username: '',
  password: '',
  host: 'localhost:80',
  hostname: 'localhost',
  port: '80',
  pathname: '/aaaa/abc',
  search: '?A=1&b=2',
  searchParams: URLSearchParams { 'A' => '1', 'b' => '2' },
  hash: ''
}
*/
export default function requestStream(options = {}) {
  const urlObj = new url.URL(options.url)
  let protocol = urlObj.protocol === 'http:' ? http : https
  const req = protocol.request(
    {
      hostname: urlObj.hostname,
      port: urlObj.port,
      path: urlObj.pathname + urlObj.search,
      method: 'POST',
      ...options,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        ...(options.headers || {})
      }
    }, (res) => {
      options.success && options.success(res)
      /* console.log(`STATUS: ${res.statusCode}`);
      console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
      res.setEncoding('utf8');
      res.on('data', (chunk) => {
        console.log(`BODY: ${chunk}`);
      });
      res.on('end', () => {
        console.log('No more data in response.')
      }) */
    });

  req.on('error', (e) => {
    console.log(`problem with request: ${e.message}`);
  });
  return req
}